<?php

namespace Gnway\Ticket\Rest\Response;

use Gnway\Ticket\Rest\Contracts\HttpResponseInterface;

class HttpResponseJson implements HttpResponseInterface
{

  /**
   * @var array
   */
  private array $value;

  /**
   * @var array
   */
  private array $httpResponseHeaders;

  /**
   * @var int
   */
  private int $httpResponseCode;

  /**
   * HttpResponseJson constructor.
   *
   * @param array $value
   * @param array $httpResponseHeaders
   * @param int   $httpResponseCode
   */
  public function __construct(array $value, array $httpResponseHeaders = [], int $httpResponseCode = 200)
  {
    $this->value = $value;
    $this->httpResponseCode = $httpResponseCode;
    $this->httpResponseHeaders = $httpResponseHeaders;
  }

  public function getValue(): string
  {
    $value = $this->_json_encode($this->value, FALSE);

    return is_string($value) ? $value : '';
  }

  public function getHttpResponseHeaders(): array
  {
    return $this->httpResponseHeaders;
  }

  public function getHttpResponseCode(): int
  {
    return $this->httpResponseCode;
  }

  /**
   * Json encode
   *
   * @param array $data
   * @param bool  $forceObject
   * @return false|string
   */
  private static function _json_encode(array $data, bool $forceObject = TRUE)
  {
    $option = (PHP_VERSION >= '5.4.0' ? JSON_UNESCAPED_UNICODE : 0) | ($forceObject ? JSON_FORCE_OBJECT : 0);
    $option = $option | (PHP_VERSION >= '5.5.0' ? JSON_PARTIAL_OUTPUT_ON_ERROR : 0);

    return json_encode($data, $option);
  }
}